import { useModel } from "umi";
import { useReactive } from "ahooks";

const useCategory = () => {
    const { remoteData } = useModel("global");

    const state = useReactive({
        categoryLoading: false,
        categories: [],
        selectedCategory: null,
        appLoading: false,
        applications: [],
        selectedApplication: null,
        submitLoading: false,
    });

    const loadCategories = async () => {
        state.categoryLoading = true;
        let res = await remoteData({
            object: "bnt-application-operation-center-service",
            serviceName: "/developer/organization/application/getCategories",
            params: {
                order: [["acName", "ASC"]],
            },
        });
        state.categories = res || [];
        setDefaultCategory();
        state.categoryLoading = false;
    };

    const setSelectedCategory = (data) => (state.selectedCategory = data);

    const setDefaultCategory = () => {
        state.selectedCategory = state.categories.find((item) => item.acName === state.selectedCategory?.acName);
        !state.selectedCategory && state.categories.length > 0 && (state.selectedCategory = state.categories[0]);
    };

    const loadCategoryApplications = async () => {
        state.appLoading = true;
        let res = await remoteData({
            object: "bnt-application-operation-center-service",
            serviceName: "/developer/organization/application/getCategoryApplications",
            params: {
                acName: state.selectedCategory.acName,
                order: [["appName", "ASC"]],
            },
        });
        state.applications = res || [];
        setDefaultApplication();
        state.appLoading = false;
    };

    const setSelectedApplication = (data) => (state.selectedApplication = data);

    const setDefaultApplication = () => {
        state.selectedApplication = state.applications.find((item) => item.appUuid === state.selectedApplication?.appUuid);
        !state.selectedApplication && state.applications.length > 0 && (state.selectedApplication = state.applications[0]);
    };

    return { ...state, loadCategories, setSelectedCategory, loadCategoryApplications, setSelectedApplication };
};

export default useCategory;
